<template>
  <div>
    <el-row class="page_top">
      <el-col :span="6">
        <el-form :model="search">
          <el-form-item prop="userName">
            <el-autocomplete
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入登录账户"
              @select="handleSelect"
              v-model="search.userName"
              clearable
              @clear="cleanSearch"
              ref="elautocomplete"
            >
              <template slot-scope="{ item }">
                <span>{{ item.label }}</span>
                <span v-show="false">{{ item.value }}</span>
              </template>
              <template slot="append">
                <el-button slot="append" icon="el-icon-search" @click="searchAll"></el-button>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="18">
        <el-button type="primary" size="small" @click="add" class="btn_add">添加</el-button>
      </el-col>
    </el-row>

    <el-table :data="lists" border style="width: 100%">
      <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
      <el-table-column label="登录账户" width="150" prop="AGENT_USERNAME"></el-table-column>
      <el-table-column label="登录密码" width="150" prop="AGENT_PASSWORD"></el-table-column>
      <el-table-column label="手机号"  width="150" prop="AGENT_PHONE"></el-table-column>
      <el-table-column label="邮箱" prop="AGENT_EMAIL"></el-table-column>
      <el-table-column label="状态" align="center" width="150">
        <template slot-scope="props">
        <span>{{ props.row.mark === 0 || props.row.mark === "0" ? '有效账户' :  '取消较多' }}</span>
      </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="管理" fixed="right" align="center" width="150">
        <template slot-scope="props">
          <!-- 修改 -->
          <el-button size="mini" @click="edit(props.row)">修改</el-button>
          <!-- 删除 -->
          <el-button type="danger" size="mini" @click="del(props.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="table-pageblock">
      <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10,20,30,40,50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 弹窗 新增or修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogShow" fullscreen>
      <!-- 添加/修改表单 -->
      <el-form label-width="100px" ref="logos" :model="logos">
        <el-row>
          <el-col :span="8">
            <el-form-item label="登录账户" prop="AGENT_USERNAME">
              <el-input v-model="logos.AGENT_USERNAME"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登录密码" prop="AGENT_PASSWORD">
              <el-input v-model="logos.AGENT_PASSWORD"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="mark">
              <el-select v-model="logos.mark" style="width:100%" placeholder="请选择">
                <el-option label="有效账户" value="0"></el-option>
                <el-option label="取消较多" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="手机号" prop="AGENT_PHONE">
              <el-input v-model="logos.AGENT_PHONE"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="AGENT_EMAIL">
              <el-input v-model="logos.AGENT_EMAIL"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" size="small" v-if="dialogTitle === '添加'" @click="create">添加</el-button>
        <el-button size="small" v-else @click="update">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Component, Vue, Prop } from "vue-property-decorator";
import { get, post } from "@/http";
import { State, Action } from "vuex-class";
import code from "../../public/cityCode.json";
import { _debounce } from "../../public/debounce.js";
import moment from "moment";

// 组件定义
@Component({
  name: "Logoslist",
  filters: {
    filterTime: value => {
      return moment(value).format("YYYY-MM-DD");
    }
  }
})
export default class Logoslist extends Vue {
  // 初始数据
  lists = [];

  // 查询条件
  search = {
    AGENT_USERNAME: "",
    userName: ""
  };

  // 远程搜索
  restaurants = [];
  // 计时器
  timeout = null;

  // 当前页
  currentPage = 1;
  // 当前数
  pageSize = 10;
  // 总条目数
  total = 20;

  // 弹窗标题
  dialogTitle = "";
  // 弹窗是否显示
  dialogShow = false;

  logos = {
    AGENT_USERNAME: "",
    AGENT_PASSWORD: "",
    AGENT_PHONE: "",
    AGENT_EMAIL: "",
    mark: ""
  };

  // 加载实例后执行
  mounted() {
    this.getLogos();
    this.loadAll();
  }

  loadAll() {
    let list = [];
    let params = {
      mark: 1
    };
    post("/api/logos/getLogosAll", params)
      .then(res => {
        if (res.success) {
          for (let i = res.data.length; i--; ) {
            list.push({
              value: res.data[i].AGENT_USERNAME,
              label: res.data[i].AGENT_USERNAME
            });
          }
          this.restaurants = list;
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

  querySearchAsync(queryString, cb) {
    let _this = this;
    let restaurants = _this.restaurants;
    let results = queryString
      ? _this.createStateFilter(queryString)
      : restaurants;
    clearTimeout(_this.timeout);
    _this.timeout = setTimeout(() => {
      cb(results);
    }, 200 * Math.random());
  }

  createStateFilter(queryString) {
    let _this = this;
    // 匹配结果
    let restaurants = _this.restaurants;
    // 搜索条件
    let state = _this.search.userName;
    // 输入值转换大写
    queryString = queryString.toUpperCase();
    let result = restaurants.filter(
      state => state.value.toUpperCase().indexOf(queryString) === 0
    );
    return result;
  }

  handleSelect(item) {
    let _this = this;
    _this.$nextTick(() => {
      _this.search.userName = item.label;
      _this.search.AGENT_USERNAME = item.value;
    });
  }

  cleanSearch() {
    let _this = this;
    _this.$nextTick(() => {
      _this.search.userName = "";
      _this.search.AGENT_USERNAME = "";
    });
  }

  // 根据选择条件查询
  searchAll() {
    let _this = this;
    let params = {
      AGENT_USERNAME:
        _this.search.AGENT_USERNAME === undefined || null
          ? ""
          : _this.search.AGENT_USERNAME,
      mark: 1,
      limit: _this.pageSize,
      offset: _this.currentPage
    };
    post("/api/logos/getLogoslist", params)
      .then(res => {
        if (res.success) {
          _this.lists = res.data.rows;
          _this.total = res.data.count;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!res.data.rows.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getLogos();
          }
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

  // 查询登录账户
  getLogos() {
    let _this = this;
    let params = {
      AGENT_USERNAME:
        _this.search.AGENT_USERNAME === undefined || null
          ? ""
          : _this.search.AGENT_USERNAME,
      mark: 1,
      limit: _this.pageSize,
      offset: _this.currentPage
    };
    post("/api/logos/getLogoslist", params)
      .then(res => {
        if (res.success) {
          _this.lists = res.data.rows;
          _this.total = res.data.count;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!res.data.rows.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getLogos();
          }
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

  // 每页显示的条数改变
  handleSizeChange(val) {
    this.pageSize = val;
    // 调用刷新页面
    this.getLogos();
  }

  // 当前页码
  handleCurrentChange(val) {
    this.currentPage = val;
    // 调用
    this.getLogos();
  }

  // 显示编辑界面
  edit(row) {
    let _this = this;
    _this.dialogTitle = "修改";
    _this.dialogShow = true;
    let info = row;
    info.mark = row.mark.toString();
    _this.logos = Object.assign({}, info);
  }

  // 显示新增界面
  add() {
    let _this = this;
    _this.dialogTitle = "添加";
    _this.dialogShow = true;
    _this.logos = {
      AGENT_USERNAME: "",
      AGENT_PASSWORD: "",
      AGENT_PHONE: "12301230123",
      AGENT_EMAIL: "test123@qq.com",
      mark: ""
    };
  }

  // 新增
  create() {
    let _this = this;
    const logbox = this.$refs["logos"];
    this.$nextTick(() => {
      logbox.validate(valid => {
        if (valid) {
          let params = {
            AGENT_USERNAME: _this.logos.AGENT_USERNAME,
            AGENT_PASSWORD: _this.logos.AGENT_PASSWORD,
            AGENT_PHONE: _this.logos.AGENT_PHONE,
            AGENT_EMAIL: _this.logos.AGENT_EMAIL,
            mark: parseInt(_this.logos.mark)
          };
          post("api/logos/addLogos", params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.getLogos();
                _this.loadAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    });
  }

  // 修改
  update() {
    let _this = this;
    const logbox = this.$refs["logos"];
    this.$nextTick(() => {
      logbox.validate(valid => {
        if (valid) {
          let params = {
            id: _this.logos.id,
            AGENT_USERNAME: _this.logos.AGENT_USERNAME,
            AGENT_PASSWORD: _this.logos.AGENT_PASSWORD,
            AGENT_PHONE: _this.logos.AGENT_PHONE,
            AGENT_EMAIL: _this.logos.AGENT_EMAIL,
            mark: parseInt(_this.logos.mark)
          };
          post("api/logos/updateLogos", params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.getLogos();
                _this.loadAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    });
  }

  // 删除客户
  del(row) {
    let _this = this;
    let params = {
      id: row.id,
      mark: 1
    };
    // 删除二次确认
    _this
      .$confirm("确认删除选中的信息吗？", "提示", {
        type: "warning"
      })
      .then(() => {
        post("/api/logos/delLogos", params)
          .then(res => {
            if (res.success) {
              this.$message({
                message: "删除成功！",
                type: "success"
              });
              _this.getLogos();
              _this.loadAll();
            }
          })
          .catch(err => {
            console.log(err);
          });
      })
      .catch(() => {
        _this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
  }
}
</script>

<style lang="scss">
.page_top {
  padding: 15px;
  .el-form-item {
    margin-bottom: 0;
  }
  .btn_add {
    margin: 5px 0;
    float: right;
  }
}

.el-dialog {
  .el-dialog__header {
    padding: 20px;
    .el-dialog__title {
      font-size: 16px;
    }
  }

  .el-dialog__body {
    padding: 0 15px;
  }
  .el-dialog__footer {
    padding-top: 0;
  }
}
</style>
